<template>

    <div >


        <div style="padding: 10px;">
            <el-button @click="refresh = true">{{$t('common.getMore')}}</el-button>
        </div>
        <commonTable :getTableList="getTableList()"
                     :refresh.sync="refresh"
                     :filter="filter"
                     :stripe="false"
                     :changeRow.sync="changeRow"
                     :dataCount="dataCount"
                     :pagination="false"
                     :selectRow.sync="selectRow"
                     :rowClassName="rowClassName"
                     :columns="columns">
        </commonTable>
        <orderEdit ref="orderEdit" :data="editData" :changeRow.sync="changeRow"></orderEdit>
    </div>
</template>

<script>

    import Tablefilter from '../components/table/commonTableFilter'
    import commonTable from '../components/table/commonTable'
    import {mapState} from 'vuex'
    import orderEdit from './orderEdit'
    import {orderState} from '../../config/index'

    export default {
        name: "auditingOrder",
        components: {
            Tablefilter,
            orderEdit,
            commonTable
        },
        data() {

            let validatemealDetils = (rule, value, callback) => {
                if (value.length === 1 && value[0].count === 0) {
                    callback(new Error(this.$t('packages.mealDetilsTip')));
                } else {
                    callback();
                }
            };

            return {
                selectRow: [],
                editData: {},
                filter: {},
                refresh: false,
                changeRow: {},
                dataCount: 10,
                columns: [
                    {label: this.$t('common.operate'), prop: 'operate', render: this.render('operate'), width: 100, tooltip: false,fixed:'right'},
                    {type: 'selection', width: 55},
                    {label: this.$t('common.productName'), prop: 'productName'},
                    {label: this.$t('common.orderId'), prop: 'orderId', width: 70},
                    {label: this.$t('common.orderState'), prop: 'orderState',render:this.render('orderState')},
                    {label: this.$t('common.orderDetail'), prop: 'orderDetail',render: this.render('orderDetail')},
                    // {label: this.$t('common.userName'), prop: 'userName'},
                    {label: this.$t('common.phoneNumber'), prop: 'phoneNumber'},
                    {label: this.$t('common.absentee'), prop: 'absentee',render: this.render('absentee')},
                    {label: 'ip', prop: 'ip'},
                    // {label: this.$t('common.userNotes'), prop: 'userNotes'},
                    {label: this.$t('common.orderTime'), prop: 'orderTime'},
                    // {label: this.$t('common.contactTime'), prop: 'contactTime', width: 90},
                    {label: this.$t('common.productNumber'), prop: 'productNumber'},
                    {label: this.$t('common.price'), prop: 'price'},
                    {label: this.$t('common.optimizer'), prop: 'optimizer'},
                    {label: this.$t('common.isVerify'), prop: 'isVerify',render:this.render('isVerify')},
                ],
                editDialog: false,
                adForm: {
                    orderId: '',
                    mealName: '',
                    mealDetils: [{id: '', count: 0}],
                },
                adFormRules: {
                    mealName: [{required: true, message: this.$t('packages.mealNameTip'), trigger: 'blur'}],
                    mealDetils: [{validator: validatemealDetils, trigger: 'blur'}],
                },
                actions:[],
                ownerOrder:{}
            }
        },
        methods: {
            search(filter) {
                this.filter = filter
                this.refresh = true
            },
            delTable(Id) {

            },
            action(key,filter) {

                if(key.value === 'exportOrder') {
                    this.exportOrder(key,filter);
                    return true
                }

                if(!this.actionCheck())return
                this.setExpressId(this.selectRow.map(v=>{return v.orderId}))
            },
            actionCheck(){
              if(this.selectRow.length==0){
                  this.$message.warning(this.$t('common.selectActionTip'))
                  return false
              }else{
                  return true
              }
            },
            addTable(Id) {
                this.editDialog = true
                this.adForm.orderId = Id ? Id : ''
            },
            getTableList() {
                return this.$getOrdersToCheck
            },
            rowClassName({row, rowIndex}) {
                if (row.orderState === 2) {
                    return 'error-row';
                } else if (row.orderState === 8) {
                    return 'info-row';
                } else if (row.orderState === 1) {
                    return 'success-row';
                }else if(rowIndex%2 === 1){
                    return 'striped-row'
                }
                return '';
            },
            render(prop) {
                let render = {}
                if (!prop) return;
                render.isVerify  =(h, params) => {
                    let render = ''
                    if (params.row.isVerify) {
                        render = this.$t('common.isVerified')
                    } else {
                        render = this.$t('common.unVerified')
                    }
                    return h('div', render)
                }
                render.operate = (h, params) => {
                    return h('div', [
                        h("el-button",
                            {
                                props: {
                                    type: 'warning',
                                    size: 'mini'
                                },
                                style: {
                                    marginLeft: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.editData = params.row
                                        this.$refs.orderEdit.changeVisiable()
                                    }
                                }
                            },
                            this.$t('common.edit')
                        )
                    ])
                }
                render.absentee  =(h, params) => {
                    let render = ''
                    if (params.row.absentee) {
                        render = this.$t('common.invalid')
                    } else {
                        render = this.$t('common.valid')
                    }
                    return h('div', render)
                }
                render.orderDetail =(h, params) => {
                    let renders = []
                    let details = this.orderDetail(params.row.orderDetail)
                    for(let [k,v] of Object.entries(details)){
                        let render = h('span',
                            v.join(' ')+'  '
                        )
                        renders.push(render)
                    }
                    return h('div',renders)
                }
                render.orderState =(h, params) => {
                    let render = this.$t('option.'+orderState[ params.row.orderState].label)
                    return h('div',render)
                }
                return render[prop]
            },
            cancelEdit() {
                this.editDialog = false
                this.resetForm()
            },
            resetForm() {
                this.$refs.adForm.resetFields()
                this.$refs.adForm.clearValidate()
            },
            confirmEdit() {
                if (!this.editCheck('adForm')) return;
                let params = {}
                Object.assign(params, this.adForm)
                if (!params.orderId) delete params.orderId
                this.$addPackage({packages: [params]}).then(response => {
                    if (response.code && response.code === 'success') {
                        this.$message.success(this.$t('common.' + params.orderId ? 'editSuccess' : 'addSuccess'))
                        this.editDialog = false
                    } else {
                        this.$message.error(this.$t('common.error'))
                    }
                })
            },
            editCheck(ref) {
                let valid = true;
                this.$refs[ref].validate((v) => {
                    valid = v
                })
                return valid
            },
            setExpressId(orderIds){
                let params = orderIds
                this.$setExpressId(params).then(response=>{
                    if(response && response.code ==='success'){
                        this.$message.success(this.$t('common.success'))
                        this.refresh = true
                    }else{
                        this.$message.error(this.$t('common.Fail'))
                    }
                })
            },
            exportOrder(key,filter){
                let params = Object.assign(filter,{expressType:key.type})

                this.$exportOrder(params).then(response=>{
                    if(response && response.code ==='success'){
                        let url = response.data;
                        window.location.href = url;

                    }else{
                        this.$message.error(this.$t('common.error'))
                    }
                })
            },
            getOrdersInfo(){
                this.$getOrdersInfo({}).then(reponse=>{
                    if(reponse && reponse.code === 'success'){
                        this.ownerOrder = reponse.data
                    }else{
                        this.ownerOrder = {}
                    }
                })
            },
            orderDetail(str){
                let attr = {}
                if(!str) return {}
                for(let [key,item] of Object.entries(JSON.parse(str))){
                    if(key === 'package') continue
                    let unique = /(.*?[)(\d*)(])/.test(key)?key.replace(/(.*?[\[])(\d*)([\]])/,'$2'):0
                    if(attr[unique]){
                        attr[unique].push(item)
                    }else{
                        attr[unique] = [item]
                    }
                }
                return attr
            },
        },
        mounted() {

        },
        watch:{
            delId(newV, oldV) {
                console.log(newV)
            }
        },
        created(){
            this.getOrdersInfo()
        },
        computed: {
            ...mapState(['countryOptions', 'productTypeOptions'])
        },
    }
</script>

<style lang="less">
    .tableInfo{
        div{
            padding-right: 20px;
            display: inline-block;
        }
    }
    .error-row{
        background-color: #f56c6c !important;
    }
    .info-row{
        background-color: #409eff !important;
    }
    .success-row{
        background-color: #67c23a !important;
    }
    .striped-row{
        background-color: #FAFAFA !important;
    }
    body .el-table__fixed-right{
        top:0.5px
    }
</style>